﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using OnePay;
using CommandLib;
using BusinessLayer.WorldArtPrice;
using BusinessLayer.WorldArtPrice.Entities;
using WorldArtPrice.Models;

namespace WorldArtPrice.Controllers
{
    public class MemberController : Controller
    {
        public  ActionResult Register()
        {            
            return View();
        }

        public ActionResult ForgotPassword()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ForgotPassword(FormCollection formCollection)
        {
            Account account = new AccountBL().GetByEmail(formCollection["email"]);
            if (account != null)
            {
                string subject = "Pass to FindArtInfo.com";
                string content = string.Format("Dear {0},<p>Please use the following information to login</p><p>Username : {1}<br>  Password : {2}</p><p>It is imperative that you maintain complete secrecy of your login and password.</p><p>findartinfo.com treats instances of invalid logins very seriously and you would   run the risk of disabling your account. Subscribers disabled for invalid logins are not allowed furtheraccess to the website. findartinfo.com reserves sole discretion in considering whether to take any action when such invalid logins are reported.</p><p>We do hope you enjoy the website and that the content is both useful and enlightening</p><p>Administrator<br>  <a href='http://findartinfo.com'>http://findartinfo.com</a><br>  Email: <a href='mailto:info@findartinfo.com'>info@findartinfo.com</a>", account.LastName, account.Email, account.PassWord);
                Utils.SendMail("noreply@findartinfo.com", "FindArtInfo.com", "findme", account.Email, account.FirstName, subject, content);
                return Content("<script language='javascript' type='text/javascript'>alert('Password sent!');window.location = '/Member/ForgotPassword';</script>");
            }
            else
                return Content("<script language='javascript' type='text/javascript'>alert('Email is not exists!');window.location = '/Member/ForgotPassword';</script>");
        }

        [HttpPost]
        public ActionResult ChangePass(FormCollection formCollection)
        {
            if (Session[Constant.SESSION_USER_LOGIN] == null)
            {
                return RedirectToAction("Index", "Home");
            }
            Account account = (Account)Session[Constant.SESSION_USER_LOGIN];
            if (!account.PassWord.Equals(formCollection["oldpass"]))
            {
                return Content("<script language='javascript' type='text/javascript'>alert('Password does not match. Try Again!!');window.location = '/Member/ChangePassword';</script>");
            }
            account.PassWord = formCollection["newpass"];
            new AccountBL().Update(account);
            return Content("<script language='javascript' type='text/javascript'>alert('Password Changed Successfully!');window.location = '/Home/Index';</script>");
        }
        
        public ActionResult ChangePassword()
        {
            return View();
        }

        public ActionResult LogOut()
        {
            Session[Constant.SESSION_USER_LOGIN] = null;
            Session[Constant.SESSION_USER_LOGIN_PAID] = null;
            return RedirectToAction("Index", "Home");
        }

        public ActionResult Detail()
        {
            if (Session[Constant.SESSION_USER_LOGIN] != null)
            {
                Account account = (Account)Session[Constant.SESSION_USER_LOGIN];                
                return View(account);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        [HttpPost]
        public ActionResult Login(FormCollection formCollection)
        {
            string email = formCollection["emailLogin"];
            string pass = formCollection["passWordLogin"];
            Account account = new AccountBL().GetByEmail(email);
            if (account == null)
            {
                return Content("<script language='javascript' type='text/javascript'>alert('Email is not exists!');window.location = '/Home/Index';</script>");
            }
            if (!account.PassWord.Equals(pass))
            {
                return Content("<script language='javascript' type='text/javascript'>alert('Incorrect Login. Please try again.');window.location = '/Home/Index';</script>");
            }
            if (account.Status == Constant.IS_NOT_ACTIVE)
            {
                return Content("<script language='javascript' type='text/javascript'>alert('Account is not active!');window.location = '/Home/Index';</script>");
            }
            TimeSpan timeSpan = account.EndDate -DateTime.Now ;
            if (timeSpan.Days < 0)
            {
                Session[Constant.SESSION_USER_LOGIN_PAID] = account;
                return Content("<script language='javascript' type='text/javascript'>alert('Account is expires!');window.location = '/Member/ReNew';</script>");
            }
            Session[Constant.SESSION_USER_LOGIN] = account;
            Session[Constant.SESSION_USER_LOGIN_PAID] = account;
            return RedirectToAction("Index", "Home");
        }

        public ActionResult LoginPaid()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LoginPaid(FormCollection formCollection)
        {
            string email = formCollection["email"];
            string pass = formCollection["pass"];
            Account account = new AccountBL().GetByEmail(email);
            if (account == null)
            {
                return Content("<script language='javascript' type='text/javascript'>alert('Email is not exists!');window.location = '/Member/LoginPaid';</script>");
            }
            if (!account.PassWord.Equals(pass))
            {
                return Content("<script language='javascript' type='text/javascript'>alert('Incorrect Login. Please try again.');window.location = '/Member/LoginPaid';</script>");
            }
            Session[Constant.SESSION_USER_LOGIN_PAID] = account;
            return RedirectToAction("ReNew", "Member");
        }

        public ActionResult ReNew()
        {
            Account account = (Account)Session[Constant.SESSION_USER_LOGIN_PAID];
            return View(account);
        }

        [HttpPost]
        public ActionResult ReNew(FormCollection formCollection)
        {
            if (Session[Constant.SESSION_USER_LOGIN_PAID] == null)
            {
                return RedirectToAction("LoginPaid", "Member");
            }
            string ipPublic=new Utils().GetPublicIP();
            Account account = (Account)Session[Constant.SESSION_USER_LOGIN_PAID];                                   
            //id giao dich thanh toan            
            string merchTxnRef = Guid.NewGuid().ToString();
            decimal amount = 0;
            new TransactionLogBL().Insert(account.Id, Convert.ToInt32(formCollection["subscription"]),
                Convert.ToInt32(formCollection["typePay"]), formCollection["couponcode"], merchTxnRef, out amount);
            if (amount == -1)
                return Content("<script language='javascript' type='text/javascript'>alert('Account is not exists!');window.location = '/Member/LoginPaid';</script>");
            if (amount == -2)
                return Content("<script language='javascript' type='text/javascript'>alert('Subscription is not exists!');window.location = '/Member/ReNew';</script>");
            if (amount > 0)
            {
                //chuyen giao dich sang ben onepay
                VPCRequest conn = new VPCRequest(Config.OnePayVitualPaymentClientURL);
                conn.SetSecureSecret(Config.OnePaySecretKey);
                // Add the Digital Order Fields for the functionality you wish to use
                // Core Transaction Fields
                conn.AddDigitalOrderField("AgainLink", "http://onepay.vn");
                conn.AddDigitalOrderField("Title", "Onepay Paygate");
                conn.AddDigitalOrderField("vpc_Locale", "en");//Chon ngon ngu hien thi tren cong thanh toan (vn/en)
                conn.AddDigitalOrderField("vpc_Version", 2.ToString());
                conn.AddDigitalOrderField("vpc_Command", "pay");
                conn.AddDigitalOrderField("vpc_Merchant", Config.OnePayMerchantId);
                conn.AddDigitalOrderField("vpc_AccessCode", Config.OnePayAccessCode);
                conn.AddDigitalOrderField("vpc_MerchTxnRef", merchTxnRef);
                conn.AddDigitalOrderField("vpc_OrderInfo", "Order Info");
                conn.AddDigitalOrderField("vpc_Amount", amount.ToString());
                conn.AddDigitalOrderField("vpc_ReturnURL", Config.OnePayUrlReturn);
                // Dia chi IP cua khach hang
                conn.AddDigitalOrderField("vpc_TicketNo", ipPublic);
                // Chuyen huong trinh duyet sang cong thanh toan
                string url = conn.Create3PartyQueryString();
                //clear session login paid
                Session[Constant.SESSION_USER_LOGIN_PAID] = null;
                return Redirect(url);
            }

            return Content("<script language='javascript' type='text/javascript'>alert('Transaction Error!');window.location = '/Member/Register';</script>");            
        }

        [HttpPost]
        public ActionResult Register(FormCollection formCollection)
        {
            //return Content("<script language='javascript' type='text/javascript'>alert('Hello world!');window.location = '/Member/Register';</script>");                    
            // Khoi tao lop thu vien va gan gia tri cac tham so gui sang cong thanh toan
            //them moi user            
            Account account=new Account();
            account.FirstName=formCollection["firstName"];
            account.LastName=formCollection["lastName"];
            account.Email=formCollection["email"];
            account.Country=formCollection["country"];
            account.Find=formCollection["find"];
            account.PassWord=formCollection["passWord"];
            //id giao dich thanh toan            
            string merchTxnRef = Guid.NewGuid().ToString();
            decimal amount = 0;
            new AccountBL().Insert(account, Convert.ToInt32(formCollection["subscription"]),
                Convert.ToInt32(formCollection["typePay"]), formCollection["couponcode"], merchTxnRef, out amount);
            if (amount == -1)
                return Content("<script language='javascript' type='text/javascript'>alert('Email Exists!');window.location = '/Member/Register';</script>");
            if (amount == -2)
                return Content("<script language='javascript' type='text/javascript'>alert('Subscription is not exists!');window.location = '/Member/Register';</script>");
            if (amount > 0)
            {
                //chuyen giao dich sang ben onepay
                VPCRequest conn = new VPCRequest(Config.OnePayVitualPaymentClientURL);
                conn.SetSecureSecret(Config.OnePaySecretKey);
                // Add the Digital Order Fields for the functionality you wish to use
                // Core Transaction Fields
                conn.AddDigitalOrderField("AgainLink", "http://onepay.vn");
                conn.AddDigitalOrderField("Title", "Onepay Paygate");
                conn.AddDigitalOrderField("vpc_Locale", "en");//Chon ngon ngu hien thi tren cong thanh toan (vn/en)
                conn.AddDigitalOrderField("vpc_Version", 2.ToString());
                conn.AddDigitalOrderField("vpc_Command", "pay");
                conn.AddDigitalOrderField("vpc_Merchant", Config.OnePayMerchantId);
                conn.AddDigitalOrderField("vpc_AccessCode", Config.OnePayAccessCode);
                conn.AddDigitalOrderField("vpc_MerchTxnRef", merchTxnRef);
                conn.AddDigitalOrderField("vpc_OrderInfo", "Order Info");
                conn.AddDigitalOrderField("vpc_Amount", amount.ToString());
                conn.AddDigitalOrderField("vpc_ReturnURL", Config.OnePayUrlReturn);
                // Dia chi IP cua khach hang
                conn.AddDigitalOrderField("vpc_TicketNo", new Utils().GetPublicIP());
                // Chuyen huong trinh duyet sang cong thanh toan
                string url = conn.Create3PartyQueryString();
                return Redirect(url);
            }

            return Content("<script language='javascript' type='text/javascript'>alert('Transaction Error!');window.location = '/Member/Register';</script>");
        }
        
        public ActionResult OnePayResponse()
        {
            string SECURE_SECRET = Config.OnePaySecretKey;
            string hashvalidateResult = "";
            // Khoi tao lop thu vien
            VPCRequest conn = new VPCRequest("http://onepay.vn");
            conn.SetSecureSecret(SECURE_SECRET);
            // Xu ly tham so tra ve va kiem tra chuoi du lieu ma hoa
            hashvalidateResult = conn.Process3PartyResponse(HttpContext.Request.QueryString);
            // Lay gia tri tham so tra ve tu cong thanh toan
            string vpc_TxnResponseCode = conn.GetResultField("vpc_TxnResponseCode", "Unknown");
            string amount = conn.GetResultField("vpc_Amount", "Unknown");
            string localed = conn.GetResultField("vpc_Locale", "Unknown");
            string command = conn.GetResultField("vpc_Command", "Unknown");
            string version = conn.GetResultField("vpc_Version", "Unknown");
            string cardType = conn.GetResultField("vpc_Card", "Unknown");
            string orderInfo = conn.GetResultField("vpc_OrderInfo", "Unknown");
            string merchantID = conn.GetResultField("vpc_Merchant", "Unknown");
            string authorizeID = conn.GetResultField("vpc_AuthorizeId", "Unknown");
            string merchTxnRef = conn.GetResultField("vpc_MerchTxnRef", "Unknown");
            string transactionNo = conn.GetResultField("vpc_TransactionNo", "Unknown");//ngan hang trả ra
            string acqResponseCode = conn.GetResultField("vpc_AcqResponseCode", "Unknown");
            string txnResponseCode = vpc_TxnResponseCode;
            string message = conn.GetResultField("vpc_Message", "Unknown");

            OnePayResponseModel onepayResponseModel = new OnePayResponseModel();

            if (hashvalidateResult == "CORRECTED" && txnResponseCode.Trim() == "0")
            {
                Account account = new AccountBL().GetByMerchTxnRef(merchTxnRef);
                if (account != null && account.Status == 0)//neu ton tai account va trang thai chua kich hoat thi gui mail kick hoat
                {
                    string tokenKey=Guid.NewGuid().ToString();
                    new AccountTokenBL().Insert(new AccountToken { AccountId = account.Id, Status = 0, TokenKey = tokenKey });
                    string subject = "Active Account";
                    string activeKey = new RijndaelEnhanced("390e1d66c75da36df7fdded5ab2f3a01", "@1B2c3D4e5F6g7H8").Encrypt(string.Format("{0}#{1}",tokenKey,merchTxnRef));
                    string content = string.Format("Please click <a href='http://localhost:30563/Member/Active/{0}'>active account</a>", Encrypt.EncodeTo64(activeKey));
                    Utils.SendMail("noreply@findartinfo.com", "FindArtInfo.com", "findme", account.Email, account.FirstName, subject, content);
                }                
                onepayResponseModel.Vpc_Result = "Transaction was paid successful";
            }
            else if (hashvalidateResult == "INVALIDATED" && txnResponseCode.Trim() == "0")
            {
                onepayResponseModel.Vpc_Result = "Transaction is pending";
            }
            else
            {
                onepayResponseModel.Vpc_Result = "Transaction was not paid successful";
            }
            onepayResponseModel.Vpc_Version = version;
            onepayResponseModel.Vpc_Amount = amount;
            onepayResponseModel.Vpc_MerchantID = merchantID;
            onepayResponseModel.Vpc_MerchantRef = merchTxnRef;
            onepayResponseModel.Vpc_OderInfor = orderInfo;
            onepayResponseModel.Vpc_ResponseCode = txnResponseCode;
            onepayResponseModel.Vpc_Command = command;
            onepayResponseModel.Vpc_TransactionNo = transactionNo;
            onepayResponseModel.Vpc_Hashvalidate = hashvalidateResult;
            onepayResponseModel.Vpc_Message = message;
            //cap nhat lai trang thai cua giao dich
            new TransactionLogBL().Approve(merchTxnRef, txnResponseCode, message);
            return View(onepayResponseModel);
        }

        public ActionResult Active(string activeKey)
        {
            string decryptActiveKey = new RijndaelEnhanced("390e1d66c75da36df7fdded5ab2f3a01", "@1B2c3D4e5F6g7H8").Decrypt(Encrypt.DecodeFrom64(activeKey));
            string tokenKey = decryptActiveKey.Split('#')[0];
            string merchTxnRef = decryptActiveKey.Split('#')[1];
            int result = -1;
            new AccountBL().ActiveAccount(tokenKey, merchTxnRef, out result);
            if (result < 0)
            {
                return Content("<script language='javascript' type='text/javascript'>alert('Account active not success!');window.location = '/Home/Index';</script>");
            }
            return Content("<script language='javascript' type='text/javascript'>alert('Account active success!');window.location = '/Home/Index';</script>");
        }
    }
}
